package com.example.qihuibao.module.splash

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.example.qihuibao.R
import com.example.qihuibao.XApplication
import com.example.qihuibao.base.BaseActivity
import com.example.qihuibao.bean.DevStat
import com.example.qihuibao.bean.RspQueryEmployInfoBean
import com.example.qihuibao.constant.Config
import com.example.qihuibao.constant.Global
import com.example.qihuibao.dao.MyDatabase
import com.example.qihuibao.databinding.ActivitySplashBinding
import com.example.qihuibao.module.main.MainActivity
import com.example.qihuibao.module.main.MainViewModel
import com.example.qihuibao.module.presentation.MyPresentation
import com.example.qihuibao.network.RetrofitManager
import com.example.qihuibao.utils.CommonUtil
import com.example.qihuibao.utils.SystemManagerUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class SplashActivity : BaseActivity<ActivitySplashBinding>(ActivitySplashBinding::inflate) {
    private var next = true
    private lateinit var vm:MainViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        vm = ViewModelProvider(this).get(MainViewModel::class.java)
        initSomeParams()
//        initView()
        downloadImage()
    }

    override fun onResume() {
        super.onResume()
//        if (!CommonUtil.isAccessibilitySettingsOn(XApplication.application)) {
//            startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
//        }else {
            if (next) {
                next = false
                lifecycleScope.launch {
                    withContext(Dispatchers.IO) {
                        loadLocalData()
                    }
                    initView()
                    Handler().postDelayed({ start(this@SplashActivity, MainActivity::class.java) }, 3000)
                }
            }
//        }
    }

    private fun initSomeParams() {
        Global.hasPresentation = MyPresentation.getDisplay() != null
        if (!Global.hasPresentation) {
            Global.isPresentationForBScreen = false
        }
    }

    private fun initView() {
        viewBinding.tvUserName.text = getString(R.string.user_name, "(食堂)")
        viewBinding.tvCanteenName.text = getString(R.string.canteen_name, "${Global.currentCanteenInfoBean?.CantName?:"***"}")
        viewBinding.tvMealName.text = getString(R.string.meal_name, "${Global.currentMealInfoBean?.MealName?:"***"}")
        viewBinding.tvMealTime.text = getString(R.string.meal_time, "${Global.currentMealInfoBean?.UseBeginTime?:"***"}")
        viewBinding.tvVersion.text = getString(R.string.version, SystemManagerUtils.getVersion())
    }

    private fun loadLocalData() {
        Global.rspQueryEnterpriseInfoBean = MyDatabase.db.enterpriseInfoDao().queryInId(Global.CorpID)
        Global.currentCanteenInfoBean = MyDatabase.db.canteenInfoDao().queryByCanteenId(Config.currentCanteenId)
        if (Global.currentCanteenInfoBean == null) {
            val list = MyDatabase.db.canteenInfoDao().queryAll()
            if (!list.isNullOrEmpty()) {
                Global.currentCanteenInfoBean = list[0]
                Config.currentCanteenId = Global.currentCanteenInfoBean!!.CantID
            }
        }
        if (Global.currentCanteenInfoBean != null) {
            val meals = MyDatabase.db.mealInfoDao().queryInCantID(Config.currentCanteenId)
            if (!meals.isNullOrEmpty()) {
                var inTime = false
                val time = System.currentTimeMillis()
                for (item in meals) {
                    if (CommonUtil.isInTime2(time, item.UseBeginTime, item.UseEndTime)) {
                        inTime = true
                        Config.currentMealId = item.MealID
                        Global.currentMealInfoBean = item
                        break
                    }
                }
                if (!inTime) {
                    var beforeTime = false
                    for (item in meals) {
                        if (CommonUtil.beforeTime(time, item.UseBeginTime)) {
                            beforeTime = true
                            Config.currentMealId = item.MealID
                            Global.currentMealInfoBean = item
                            break
                        }
                    }
                    if (!beforeTime) {
                        Config.currentMealId = meals[0].MealID
                        Global.currentMealInfoBean = meals[0]
                    }
                }
            }
        }
        parseInitialQRCode()
    }

    private fun downloadImage() {
        //todo download start img
//        vm.getSplashImage().observe(this) {
//            if (it?.success == true && !it.imageUrl.isNullOrEmpty()) {
//                Config.splashImageUrl = it.imageUrl
//            }
//            Glide.with(this)
//                .load(Config.splashImageUrl)
//                .placeholder(R.drawable.ic_splash_logo)
//                .into(viewBinding.ivSplashLogo)
//        }
//        vm.testPost(MyBean("cww")).observe(this) {
//            //
//        }
    }

    private fun parseInitialQRCode() {
        val list = Config.INITIAL_QRCODE_CONTENT.split("|")
        if (list.size == 5) {
            repeat(list.size) {
                when(it) {
                    0 -> Global.serverUrl = "http://${list[it]}"
                    1 -> Global.CorpID = list[it]
                    2 -> Global.canteenId = list[it]
                    3 -> Global.CorpName = list[it]
                    4 -> Global.CorpKey = list[it]
                }
            }
            RetrofitManager.getInstance().resetRetrofit()
        }
    }

}